package com.baitiaojun.user.support;

import com.baitiaojun.api.util.AESUtil;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.FileUtil;
import com.baitiaojun.api.util.HttpUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @类名 FastdfsSuppoert
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/1/4 20:58
 * @版本 1.0
 */
@Component
public class FastdfsSupport {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${fdfs.host}")
    private String host;

    @Value("${fdfs.port}")
    private String port;

    public void getUserAvatar(String group, HttpServletRequest request, HttpServletResponse response, String filePath) throws Exception {
        //定义访问文件服务器的url
        StringBuilder urlStr = new StringBuilder("http://");
        urlStr.append(host).append(":").append(port).append("/").append(group).append("/").append(filePath);
        String url = urlStr.toString();
        //获取请求头参数的名称列表进行遍历，然后把参数名称对应的值添加到一个map中
        Map<String,Object> headers = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        String headerName;
        while (headerNames.hasMoreElements()) {
            headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        //通过获取FIleInfo得到总文件大小
        long fileSize = fastFileStorageClient.queryFileInfo(group, filePath).getFileSize();
        //	2、accept-range：bytes
        //	3、content-type：image/jpeg
        response.setHeader("Accept-Ranges", "bytes");
        response.setContentLength((int) fileSize);
        //使用httputil的get方法得到outputstream进行输出，参数为map、response、url
        HttpUtil.get(url, headers, response);
    }

    public String uploadUserAvatar(MultipartFile multipartFile) throws Exception {
        InputStream inputStream = multipartFile.getInputStream();
        String extName = FileUtil.getfileExtName(multipartFile.getName());
        StorePath storePath = fastFileStorageClient.uploadFile(ConstantUtil.UPLOAD_AVATAR_FILE_GROUP
                                                                , inputStream, multipartFile.getSize(), extName
        );
        AESUtil aesUtil = new AESUtil(ConstantUtil.AES_SEED);
        return aesUtil.encrypt(storePath.getFullPath());
    }
}
